#include "config.h"

#include <stdint.h>
#include <errno.h>


#define DBG_SUBSYS S_LIBYLIB

#include "sequence.h"
#include "sysy_lib.h"
#include "dbg.h"

static uint64_t __sequence__;
static int __sequence_fd__;

int sequence_get(uint64_t *sequence)
{
        int ret;

        *sequence = __sequence__++;

        ret = pwrite(__sequence_fd__, &__sequence__, sizeof(__sequence__), 0);
        if (ret < 0) {
                ret = errno;
                GOTO(err_ret, ret);
        }

        YASSERT(ret == sizeof(__sequence__));

        return 0;
err_ret:
        return ret;
}

int sequence_init(const char *home)
{
        int ret, fd;
        char path[MAX_PATH_LEN];

        snprintf(path, MAX_PATH_LEN, "%s/status/sequence", home);

        fd = open(path, O_CREAT | O_RDWR, 0644);
        if (fd == -1) {
                ret = errno;
                GOTO(err_ret, ret);
        }

        ret = pread(fd, &__sequence__, sizeof(__sequence__), 0);
        if (ret < 0) {
                ret = errno;
                GOTO(err_ret, ret);
        }

        if (ret == 0) {
                __sequence__ = 0;

                ret = pwrite(fd, &__sequence__, sizeof(__sequence__), 0);
                if (ret < 0) {
                        ret = errno;
                        GOTO(err_ret, ret);
                }

                YASSERT(ret == sizeof(__sequence__));
        }

        __sequence_fd__ = fd;
        return 0;
err_ret:
        return ret;
}
